/**
 * Created by MBENBEN on 2016/10/25.
 */

var sState='signin';
var adSource=''

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //
    var r = window.location.search.substr(1).match(reg);  //
    if (r != null) return unescape(r[2]);
    return null; //
}
function setCookie(name,value,time)
{
    var Days = time;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
}
function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}
$(document).ready(function() {
    if(getUrlParam('type')){
        $('#'+getUrlParam('type')).fadeIn(500);
        //console.log('#'+getUrlParam('type'))

        if(getUrlParam('type')!='signin'&&getUrlParam('type')!='signup'){
            $('#sign').fadeOut(500)
            $('.panel-body').fadeIn(500);
        }

        sState=getUrlParam('type')
    }else{
        $('#signin').fadeIn(500);
        $('#sign').fadeIn(500)
    }
    if(getUrlParam('from')){
        adSource=getUrlParam('from');
    }

    if(sState=='signin'){
        if (getCookie("rmbUser") == "true") {
            $("#isKeep").prop("checked", true);
            $("#email").val(getCookie("email"));
            //$("#password").remove();
            //$("#pass").append("<input id='password' type='password' class='txt2'/>");
            $("#password").val(getCookie("password"));
        }
    }
    var checkEmail = function(obj){
        var emailElem = obj.find('input[name="email"]');
        var isValid =  !!(emailElem.val().match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/g));
        if(!isValid){
            var warnView = obj.find('.warn-email');
            warnView.find('.hint-illegal').fadeIn(500);
            warnView.find('.hint-dup').fadeOut(500);
            warnView.fadeIn();
        }
        return isValid;
    };

    $('.panel-header span').on("click",function(){
          var nowId=$(this).index()
          switch (nowId){
              case 0 :
                  $('#signin').fadeIn();
                  $('#signup').fadeOut(500);
                  $('.panel-header span').eq(0).addClass('sign-border')
                  $('.panel-header span').eq(1).removeClass('sign-border')
                  sState='signin'
                  break;
              case 1:
                  $('#signup').fadeIn();
                  $('#signin').fadeOut(500);
                  $('.panel-header span').eq(1).addClass('sign-border')
                  $('.panel-header span').eq(0).removeClass('sign-border')
                  sState='signup'
                  break;
          }
    })


    $('.lost-pass').on('click',function(){
        $('#sign').fadeOut(500);
        $('#forword').fadeIn();
        $('#word').fadeIn();
        sState='word'
    })
    $('.back-pass').on('click',function(){
        $('#sign').fadeIn();
        $('#forword').fadeOut(500);
        $('#word').fadeOut(500);
        sState='signin'
    })


    var emailInput = $('input[name="email"]')
    var passInput = $('input[name="password"]')
    $('.btn-rulily-sign-in').on('click', function () {
        var $this=$(this)
        var $parent=$this.parent().parent();
        var signUrl,signData;
        if ($parent.find('input[name="email"]').val() == ''){
            $parent.find('input[name="email"]').next().show(300);
            setTimeout(function () {
                $parent.find('input[name="email"]').next().hide(300);
            }, 2000);
            return
        }
       // console.log('010')
        if(sState!='resetDiv'||sState!='reset'){
            //if(!checkEmail($this.parents('.panel-body'))){
            //    $parent.find('input[name="email"]').next().show(300);
            //    $parent.find('input[name="email"]').next().html('Unregistered email')
            //    setTimeout(function () {
            //        $parent.find('input[name="email"]').next().hide(300);
            //    }, 2000);
            //    return
            //}
        }
        switch (sState){
            case 'signin':
                //console.log('011')
                if($parent.find('input[name="password"]').val() == '') {
                    $parent.find('input[name="password"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="password"]').next().hide(300);
                    }, 2000);
                    return
                }
                signUrl='http://search.rulili.com/m/tbkAuth/login'
                signData={
                    loginName:$parent.find('input[name="email"]').val(),
                    password:$parent.find('input[name="password"]').val()
                }
                break;
            case 'signup':
               // console.log('012')
                if($parent.find('input[name="password"]').val() == '') {
                    $parent.find('input[name="password"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="password"]').next().hide(300);
                    }, 2000);
                    return
                }
                if($parent.find('input[name="nickname"]').val() == '') {
                    $parent.find('input[name="nickname"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="nickname"]').next().hide(300);
                    }, 2000);
                    return
                }
                signUrl='login/signup.do'
                signData={
                    email:$parent.find('input[name="email"]').val(),
                    passwd:$parent.find('input[name="password"]').val(),
                    nickname:$parent.find('input[name="nickname"]').val(),
                    adSource:adSource
                }
                break;
            case 'word':
                signUrl='login/password/restEmail.do'
                signData={
                    email:$parent.find('input[name="email"]').val(),
                }
                break;
            case 'addEmail':
                if($parent.find('input[name="password"]').val() == '') {
                    $parent.find('input[name="password"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="password"]').next().hide(300);
                    }, 2000);
                    return
                }
                signUrl='user/addEmail.do'
                signData={
                    email:$parent.find('input[name="email"]').val(),
                    passwd:$parent.find('input[name="password"]').val()
                }
                break;
            case 'resetDiv':

                if($parent.find('input[name="newpassword"]').val() == '') {
                    $parent.find('input[name="newpassword"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="newpassword"]').next().hide(300);
                    }, 2000);
                    return
                }
                if($parent.find('input[name="confirmpassword"]').val() == '') {
                    $parent.find('input[name="confirmpassword"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="confirmpassword"]').next().hide(300);
                    }, 2000);
                    return
                }
                if($parent.find('input[name="confirmpassword"]').val() != $parent.find('input[name="newpassword"]').val()) {
                    $parent.find('input[name="confirmpassword"]').next().show(300);
                    setTimeout(function () {
                        $parent.find('input[name="confirmpassword"]').next().hide(300);
                    }, 2000);
                    return
                }
                signUrl='user/addEmail.do'
                signData={
                    e:getUrlParam('e'),
                    passwd:$parent.find('input[name="confirmpassword"]').val()
                }
                break;
        }
        var $this=$(this)
        var oldHtml=$this.html()
        if($this.html()!='loading...') {
            $this.html('loading...')
           // console.log('013',signUrl)

            $.ajax({
                type: 'POST',
                //url: 'http://127.0.0.1:3000/users/login',
                url:'/users/login',
                data: signData,
                success: function (data) {
                    if (data.success) {
                       // console.log(data,data.code,data.tbkToken)

                            if(sState=='signin'){
                                setCookie('login_name',data.data.username,3)
                            }
                            window.location.href='index.html'

                       // ('#successModal').modal('show')
                        setTimeout(function () {
                           // window.location.href=httpUrl+'dashboard.html'
                        }, 2000);
                        $this.html(oldHtml)
                    } else {
                        $('.ac-pa-error-n').fadeIn()
                        $('.ac-pa-error-n').html(data.msg)
                        setTimeout(function () {
                            $('.ac-pa-error').fadeOut()
                        }, 3000);
                        $this.html(oldHtml)
                    }

                }, error: function () {
                    $this.html(oldHtml)
                }
            });
        }


    })
})
//function callback(data){
//    console.log(data)
//}
function save() {
    if ($("#isKeep").prop("checked")) {
        var username = $("#email").val();
        var password = $("#password").val();
        setCookie("rmbUser", "true", 7); //
        setCookie("email", username, 7);
        setCookie("password", password, 7);
    }else{
        setCookie("rmbUser", "false", -1);
        setCookie("email", "", -1);
        setCookie("password", "",-1);
    }
};
